package com.odata.mediawiki;

import org.odata4j.examples.JaxRsImplementation;
import org.odata4j.examples.ODataServerFactory;
import org.odata4j.producer.resources.DefaultODataProducerProvider;

/**
 * Web service endpoint for Media Wiki website.
 * It creates endpoint for given media wiki website passed as an argument to the program.
 * By default, it creates an OData endpoint for Wikipedia.
 *
 * @author Aashish Salokhe
 * @author Kedar Deshpande
 * @since 1.0
 */
@Copyright
public class ODataMediaWikiEndpoint {

	final static String USAGE = "Invalid Program Arguments\n" +
				"USAGE: <program_name> [-domain <domain>] [-scriptpath <scriptpath>] [-port <port>] [-service <service_name>]";

	public static void main(String[] args) {
		DefaultODataProducerProvider.setInstance(new MediaWikiProducer());
		new ODataServerFactory(JaxRsImplementation.JERSEY).hostODataServer(initArgs(args));
	}

	/**
	 * Initializes the parameters required parameters for the endpoint according to the arguments passed to the program.
	 * @param args Array of string arguments
	 * @return URL of the service endpoint constructed according to the arguments.
	 */
	private static String initArgs(String[] args) {
		/**
		 * USAGE: <program_name> [-domain <domain>] [-scriptpath <scriptpath>] [-port <port>] [-service <service_name>]
		 */
		String domain = Constants.WIKIPEDIA_DOMAIN;
		String scriptPath = "";
		String port = Constants.DEFAULT_PORT;
		String serviceName = Constants.ODATA_MEDIAWIKI_SVC_NAME;
		if(args.length%2 != 0) {
			System.out.println(USAGE);
			System.exit(1);
		}
		for(int i=0; i < args.length; i+=2) {
			switch (args[i]) {
				case "-domain": domain = args[i+1]; break;
				case "-scriptpath": scriptPath = args[i+1]; break;
				case "-port": port = args[i+1]; break;
				case "-service": serviceName = args[i+1]; break;
				default: System.out.println(USAGE); System.exit(1);
			}
		}
		MediaWikiProducer.setParameter(domain, scriptPath);
		return "http://localhost:" + port + "/" + serviceName + ".svc/";
	}
}